package com.ruoyi.activiti.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.ruoyi.activiti.constanst.ProcessType;
import com.ruoyi.activiti.domain.CheckTask;
import com.ruoyi.activiti.domain.InstanceBusiness;
import com.ruoyi.activiti.mapper.CheckTaskMapper;
import com.ruoyi.activiti.mapper.TaskMapper;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.activiti.mapper.BizLeaveMapper;
import com.ruoyi.activiti.domain.BizLeave;
import com.ruoyi.activiti.service.IBizLeaveService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 请假Service业务层处理
 *
 * @author 一只闲鹿
 * @date 2020-11-29
 */
@Service
@AllArgsConstructor
public class BizLeaveServiceImpl implements IBizLeaveService
{
    private BizLeaveMapper bizLeaveMapper;
    private IProcessService processService;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private CheckTaskMapper checkTaskMapper;

    /**
     * 查询请假
     *
     * @param id 请假ID
     * @return 请假
     */
    @Override
    public BizLeave selectBizLeaveById(Long id)
    {
        return bizLeaveMapper.selectBizLeaveById(id);
    }

    @Override
    public BizLeave selectBizLeaveByInstanceId(String instanceId) {
        return bizLeaveMapper.selectBizLeaveByInstanceId(instanceId);
    }

    /**
     * 查询请假列表
     *
     * @param bizLeave 请假
     * @return 请假
     */
    @Override
    public List<BizLeave> selectBizLeaveList(BizLeave bizLeave)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            bizLeave.setCreateBy(SecurityUtils.getUsername());
        }
        List<BizLeave> list = bizLeaveMapper.selectBizLeaveList(bizLeave);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }
    @Transactional
    @Override
    public void checkTask(CheckTask checkTask) {
        String userName = SecurityUtils.getUsername();
        checkTask.setCreatedBy(userName);
        checkTask.setCreatedTime(LocalDateTime.now());
        checkTaskMapper.insert(checkTask);
        Map<String,String> map = new HashMap<>();
        map.put("pass",checkTask.getReviewStatus());
        map.put("comment",checkTask.getReason());
        String vars = JSON.toJSONString(map);
        processService.complete(checkTask.getTaskId(),checkTask.getInstanceId(),vars);
    }

    @Override
    public CheckTask selectByInstanceId(CheckTask checkTask) {
        return checkTaskMapper.queryByInstanceId(checkTask);
    }

    /**
     * 新增请假
     *
     * @param bizLeave 请假
     * @return 结果
     */
    @Override
    public int insertBizLeave(BizLeave bizLeave)
    {
        bizLeave.setCreateBy(SecurityUtils.getUsername());
        bizLeave.setCreateTime(DateUtils.getNowDate());
        return bizLeaveMapper.insertBizLeave(bizLeave);
    }

    /**
     * 修改请假
     *
     * @param bizLeave 请假
     * @return 结果
     */
    @Override
    public int updateBizLeave(BizLeave bizLeave)
    {
        bizLeave.setUpdateTime(DateUtils.getNowDate());
        return bizLeaveMapper.updateBizLeave(bizLeave);
    }

    /**
     * 批量删除请假
     *
     * @param ids 需要删除的请假ID
     * @return 结果
     */
    @Override
    public int deleteBizLeaveByIds(Long[] ids)
    {
        return bizLeaveMapper.deleteBizLeaveByIds(ids);
    }

    /**
     * 删除请假信息
     *
     * @param id 请假ID
     * @return 结果
     */
    @Override
    public int deleteBizLeaveById(Long id)
    {
        return bizLeaveMapper.deleteBizLeaveById(id);
    }
    public void submitApply(Long id) throws Exception {
        BizLeave bizLeave = selectBizLeaveById(id);
        Map<String,Object> data = new HashMap<>();
        data.put("name",bizLeave.getTitle());
        data.put("type", "请假");
        Map<String,Object> vars = new HashMap<>();
        vars.put("data",data);
        String instanceId = processService.submitApply("leave",vars);
        String username = SecurityUtils.getUsername();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date now = new Date();
        bizLeave.setInstanceId(instanceId);
        bizLeave.setApplyUserName(nickName);
        bizLeave.setApplyUserId(username);
        bizLeave.setApplyTime(now);
        bizLeave.setUpdateBy(nickName);
        bizLeave.setUpdateTime(now);
        bizLeave.setProcessKey("leave");
        updateBizLeave(bizLeave);
        InstanceBusiness ib = new InstanceBusiness();
        ib.setInstanceId(instanceId);
        ib.setBusinessKey(id + "");
        ib.setModule(humpToLine(bizLeave.getClass().getSimpleName()).substring(1));
        taskMapper.insertInstanceBusiness(ib);
    }
    private String humpToLine(String str) {
        Pattern humpPattern = Pattern.compile("[A-Z]");
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
